package com.blue.gateway.paycore.wxpay.refund;

import com.alibaba.fastjson.JSON;
import com.blue.gateway.config.BaseChannelConfig;
import com.blue.gateway.annotation.Channel;
import com.blue.gateway.common.Request;
import com.blue.gateway.common.request.RefundRequest;
import com.blue.gateway.common.response.RefundResponse;
import com.blue.gateway.config.WxConfig;
import com.blue.gateway.paycore.AbstractBaseChannelService;
import com.blue.gateway.paycore.wxpay.WxPayConstants;
import com.blue.gateway.dto.Result;
import com.blue.gateway.dto.ResultWrapper;
import com.blue.gateway.enums.PayChannelEnum;
import com.blue.gateway.enums.ResultCodeEnum;
import com.blue.gateway.enums.ServiceChannelEnum;
import com.blue.gateway.utils.RandomUtil;
import com.blue.gateway.utils.XmlUtil;
import com.blue.gateway.utils.http.HttpClientsUtil;
import com.blue.gateway.utils.sign.WxPaySignature;
import lombok.extern.slf4j.Slf4j;
import org.apache.commons.lang3.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;

import java.util.Map;
import java.util.TreeMap;

/**
 * @author xiaoyiming
 * @date 2020/5/4 22:53
 * @depiction
 */
@Slf4j
@Channel(PayChannel = PayChannelEnum.WX, ServiceChannel = ServiceChannelEnum.REFUND_QUERY)
public class WxRefundQueryService extends AbstractBaseChannelService {

    @Autowired
    private WxConfig wxConfig;

    @Override
    public Result validate(Request request) {
        RefundRequest refundRequest = (RefundRequest) request;
        if (StringUtils.isEmpty(refundRequest.getTradeNo())
                && StringUtils.isEmpty(refundRequest.getOutTradeNo())
                && StringUtils.isEmpty(refundRequest.getRefundTradeNo())
                && StringUtils.isEmpty(refundRequest.getOutRequestNo())) {
            return ResultWrapper.fail(ResultCodeEnum.CONFIG_ILLEGAL);
        }
        return ResultWrapper.success();
    }

    @Override
    public BaseChannelConfig getConfig(Request request) {
        return wxConfig;
    }

    @Override
    public String generateParams(Request request, BaseChannelConfig channelConfig) {
        RefundRequest payRequest = (RefundRequest) request;
        WxConfig wxConfig = (WxConfig) channelConfig;

        Map<String, String> params = new TreeMap<>();
        params.put("appid", wxConfig.getAppId());
        params.put("mch_id", wxConfig.getMchId());
        params.put("nonce_str", RandomUtil.getRandomStr());
        if (StringUtils.isNotEmpty(payRequest.getTradeNo())) {
            params.put("transaction_id", payRequest.getTradeNo());
        }
        if (StringUtils.isNotEmpty(payRequest.getOutTradeNo())) {
            params.put("out_trade_no", payRequest.getOutTradeNo());
        }
        if (StringUtils.isNotEmpty(payRequest.getOutRequestNo())) {
            params.put("out_refund_no", payRequest.getOutRequestNo());
        }
        if (StringUtils.isNotEmpty(payRequest.getRefundTradeNo())) {
            params.put("refund_id", payRequest.getRefundTradeNo());
        }
        String sign = WxPaySignature.sign(params, wxConfig.getParterKey());
        params.put("sign", sign);
        return XmlUtil.mapToXML(params);
    }

    @Override
    public String execute(String requestParams, BaseChannelConfig channelConfig) {
        // 发送请求
        String executeResult = null;
        try {
            executeResult = HttpClientsUtil.httpClientPost(WxPayConstants.WX_REFUND_QUERY_GATEWAY, requestParams);
        } catch (Exception e) {
            // do nothing
        }
        return executeResult;
    }

    /**
     * <xml>
     * <appid><![CDATA[wxd898fcb01713c658]]></appid>
     * <err_code><![CDATA[REFUNDNOTEXIST]]></err_code>
     * <err_code_des><![CDATA[not exist]]></err_code_des>
     * <mch_id><![CDATA[1483469312]]></mch_id>
     * <nonce_str><![CDATA[5Zr9pHvS14oY7w9h]]></nonce_str>
     * <result_code><![CDATA[FAIL]]></result_code>
     * <return_code><![CDATA[SUCCESS]]></return_code>
     * <return_msg><![CDATA[OK]]></return_msg>
     * <sign><![CDATA[384F77369C3BE60521C14FEB7A1D1250]]></sign>
     * </xml>
     *
     * @param executeResult
     * @return
     */
    @Override
    public Result analysisResult(String executeResult) {
        RefundResponse payResponse = new RefundResponse();
        Map<String, String> result = XmlUtil.toMap(executeResult);
        payResponse.setMsg(result.get("return_msg"));
        payResponse.setData(JSON.toJSONString(result));
        if (WxPayConstants.SUCCESS.equals(result.get("return_code"))) {
            return ResultWrapper.success(payResponse);
        }

        return ResultWrapper.fail(payResponse);
    }
}
